package com.colin.userservice.exception;

import com.colin.response.R;
import com.colin.response.RCM;
import com.colin.userservice.exception.sub.PasswordErrorException;
import com.colin.userservice.exception.sub.UserNotExistException;
import com.colin.userservice.exception.sub.UsernameExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(RegisterException.class)
    public R<Boolean> registerExceptionHandeler(RegisterException exception) {
        if (exception instanceof UsernameExistException) {
            return R.error(RCM.USER_EXISTS);
        }
        return R.error(RCM.USER_REGISTER_ERROR);
    }

    @ExceptionHandler(AccessException.class)
    public R<Boolean> accessExceptionHandeler(AccessException exception) {
        if (exception instanceof UserNotExistException) {
            return R.error(RCM.USER_NOT_EXISTS);
        }
        if (exception instanceof PasswordErrorException) {
            return R.error(RCM.USER_PASSWORD_ERROR);
        }
        return R.error(RCM.USER_LOGIN_ERROR);
    }

    @ExceptionHandler(SQLException.class)
    public R<Boolean> sqlExceptionHandeler(SQLException exception) {
        log.error(exception.getMessage());
        return R.error(RCM.SQL_ERROR);
    }
}
